package com.example.consume;

import com.example.utils.RabbitMqUtils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class Consumer {
    //队列名称
    public static final String QUEUE_NAME = "hello1";

    //发送消息到队列中
    public static void getMS(int second) {
        Channel channel = RabbitMqUtils.getChannel();
        try {
            channel.basicQos(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /* 接收消息[消费者要处于监听的状态才会执行回调函数] basicConsume
         * 1.消费那个队列
         * 2.消费成功后是否要自动应答
         * 3.消费者未成功消费的回调
         * 4，消费者取消消费的回调
         */
        //消息消费成功回调函数
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            System.out.println(new String(delivery.getBody()));
            try {
                TimeUnit.SECONDS.sleep(second);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //手动应答 参数1:消息的唯一标识    参数2:是否批量应答
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), true);
        };
        //取消消息时触发的回调函数
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("消息消费错误");
        };
        try {
            //channel绑定队列，autoAck为true表示一旦收到消息则自动回复确认消息
            channel.basicConsume(QUEUE_NAME, false, deliverCallback, cancelCallback);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
